<?php
namespace app\admin\controller;
use think\Controller;

class User extends Controller
{
    /**
     * 用户列表
     */
    public function userlist(){
        $data = Db('user')->where('audit',1)->order('id desc')->paginate(10);
        $page = $data->render();
        $this->assign('page',$page);
        $this->assign('data',$data);
        return view('user/index');
    }


    /**
     * 文件上传
     */
    public function upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
        // 成功上传后 获取上传信息
        // 输出 jpg
            echo $info->getExtension();
        // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            echo $info->getSaveName();
        // 输出 42a79759f284b767dfcb2a0197904287.jpg
            echo $info->getFilename();
        }else{
        // 上传失败获取错误信息
            echo $file->getError();
        }
    }



    /**
     * 用户编辑
     */
    public function edit($id){
        if(request()->isPost()){
            $post = input('post.');
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('image');
            if(!empty($file)){
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){
                    // 成功上传后 获取上传信息
                    // 输出 jpg
                    $info->getExtension();
                    // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                    $info->getSaveName();
                    // 输出 42a79759f284b767dfcb2a0197904287.jpg
                    $post['headimage'] = $info->getFilename();

                }else{
                    // 上传失败获取错误信息
                    $file->getError();
                }
            }else{
                $post['headimage'] = '';
            }
            //判断修改过后的邮箱时候在后缀列表中
            // $email = substr(strstr($post['email'],'@'),1);
            // $test = Db('suffix')->where('suffix',$email)->find();
            // if($test){
            //     $audit = 1;
            // }else{
            //     $audit = 0;
            // }
            $num = Db('user')->where('id',$id)->update(['email'=>$post['email'],'company'=>$post['company'],'position'=>$post['position'],'username'=>$post['username'],'headimage'=>$post['headimage'],'audit'=>$post['audit']]);
            if($num>0){
                $this->success('更新成功');
            }else{
                $this->error('更新失败');
            }
        }
        $data = Db('user')->where('id',$id)->find();
        $this->assign('data',$data);
        return view('user/edit');
    }



    /**
     * 用户添加
     */
    public function add(){
        if(request()->isPost()){
            $post = input('post.');
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('image');
            if(!empty($file)){
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){
                    // 成功上传后 获取上传信息
                    // 输出 jpg
                    $info->getExtension();
                    // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                    $info->getSaveName();
                    // 输出 42a79759f284b767dfcb2a0197904287.jpg
                    $post['headimage'] = $info->getFilename();

                }else{
                    // 上传失败获取错误信息
                    $file->getError();
                }
            }else{
                $post['headimage'] = '';
            }
            //判断修改过后的邮箱时候在后缀列表中
            $email = substr(strstr($post['email'],'@'),1);
            $test = Db('suffix')->where('suffix',$email)->find();
            if($post['audit'] == 1){
                if(empty($test)){
                    Db('suffix')->insert(['suffix'=>$email,'creat_time'=>date('y-m-d h:i:s')]);
                }
            }

            $num = Db('user')->insert(['email'=>$post['email'],'audit'=>$post['audit'],'company'=>$post['company'],'position'=>$post['position'],'username'=>$post['username'],'headimage'=>$post['headimage'],'password'=>md5($post['password'])]);
            if($num>0){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }

        }
        return view('user/add');
    }


    /**
     * 用户删除
     */
    public function delete(){
        if(request()->isPost()){
            $post = input('post.');
            $id = $post['uid'];
            if(!empty($id)){
                $num = Db('user')->where('id',$id)->delete();
                if($num>0){
                    //删除成功
                    return 1;
                }else{
                    //删除失败
                    return 2;
                }
            }else{
                //id不存在
                return 3;
            }
        }else{
            //请求格式不对
            return 4;
        }
    }

    /**
     * 导出
     */
    public function export(){
        $xlsData = Db('user')->select();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        $objExcel = new \PHPExcel();
        //set document Property
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

        $objActSheet = $objExcel->getActiveSheet();
        $key = ord("A");
        $letter =explode(',',"A,B,C,D,E,F");
        $arrHeader = array('姓名','公司','职位','邮箱','状态');
        //填充表头信息
        $lenth =  count($arrHeader);
        for($i = 0;$i < $lenth;$i++) {
            $objActSheet->setCellValue("$letter[$i]1","$arrHeader[$i]");
        };
        //填充表格信息
        foreach($xlsData as $k=>$v){
            $k +=2;
            $objActSheet->setCellValue('A'.$k,$v['username']);
            $objActSheet->setCellValue('B'.$k, $v['company']);
            // // 图片生成
            // $objDrawing[$k] = new \PHPExcel_Worksheet_Drawing();
            // $objDrawing[$k]->setPath('public/static/admin/images/profile_small.jpg');
            // // 设置宽度高度
            // $objDrawing[$k]->setHeight(40);//照片高度
            // $objDrawing[$k]->setWidth(40); //照片宽度
            // /*设置图片要插入的单元格*/
            // $objDrawing[$k]->setCoordinates('C'.$k);
            // // 图片偏移距离
            // $objDrawing[$k]->setOffsetX(30);
            // $objDrawing[$k]->setOffsetY(12);
            // $objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet());
            // 表格内容
            $objActSheet->setCellValue('C'.$k, $v['position']);
            $objActSheet->setCellValue('D'.$k, $v['email']);
            $objActSheet->setCellValue('E'.$k, $v['statuid'] == 1?'正常':'失效');


            // 表格高度
            $objActSheet->getRowDimension($k)->setRowHeight(20);
        }

        $width = array(20,20,15,10,10,30,10,15);
        //设置表格的宽度
        $objActSheet->getColumnDimension('A')->setWidth($width[5]);
        $objActSheet->getColumnDimension('B')->setWidth($width[1]);
        $objActSheet->getColumnDimension('C')->setWidth($width[0]);
        $objActSheet->getColumnDimension('D')->setWidth($width[5]);
        $objActSheet->getColumnDimension('E')->setWidth($width[5]);


        $outfile = "人员表.xls";
        ob_end_clean();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$outfile.'"');
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter->save('php://output');
    }

    /**
     * 修改状态
     */
    public function changestatus(){
        if(request()->isPost()){
            $post = input('post.');
            $id = $post['id'];
            $statuid = $post['statuid'];
            if($statuid == 1){
                $statuid = 0;
                $num = Db('user')->where('id',$id)->update(['audit'=>$statuid]);
                if($num>0){
                    return json(['statuid'=>$statuid,'msg'=>'修改成功']);
                }else{
                    $statuid = 1;
                    return json(['statuid'=>$statuid,'msg'=>'修改失败']);
                }
            }else{
                $statuid = 1;
                $num = Db('user')->where('id',$id)->update(['audit'=>$statuid]);
                if($num>0){
                    return json(['statuid'=>$statuid,'msg'=>'修改成功']);
                }else{
                    $statuid = 0;
                    return json(['statuid'=>$statuid,'msg'=>'修改失败']);
                }
            }
        }
    }


    /**
     * 用户后缀审核
     */
    public function audit(){
        if(request()->isPost()){
            $param = input('param.');
            $data['audit'] = 1;
            $num = Db('user')->where('id',$param['uid'])->update(['audit'=>$data['audit']]);

            if($num>0){
                //通过后添加到后缀表
                $email = substr(strstr($param['suffix'],'@'),1);
                $test = Db('suffix')->where('suffix',$email)->find();
                if(empty($test)){
                    $test = Db('suffix')->insert(['suffix'=>$email,'creat_time'=>date('y-m-d h:i:s')]);
                    if($test == 1){
                        //把user表中同后缀的用户全部通过
                        $where['audit'] = 0;
                        $where['email'] = ['like',"%$email%"];
                        $suffix = Db('user')->where($where)->select();
                        foreach ($suffix as $k => $v) {
                            Db('user')->where('id',$v['id'])->update(['audit'=>1]);
                            //发送邮件通知用户审核通过
                            $toemail=$v['email'];
                            $name='VDMA';
                            $subject='VDMA China: Your VDMA Wechat Account Status';
                            $content="Dear VDMA members,Thank you for using VDMA China Wechat, your account is now ready to login.Thank you for your cooperation.";
                            $this->send_mail($toemail,$name,$subject,$content);
                        }
                        return ['code'=>1,'msg'=>'修改成功'];
                    }
                }else{
                    $test = Db('suffix')->where('suffix',$email)->update(['statuid'=>1]);
                    if($test == 1){
                        //把user表中同后缀的用户全部通过
                        $where['audit'] = 0;
                        $where['email'] = ['like',"%$email%"];
                        $suffix = Db('user')->where($where)->select();
                        foreach ($suffix as $k => $v) {
                            Db('user')->where('id',$v['id'])->update(['audit'=>1]);
                            //发送邮件通知用户审核通过
                            $toemail=$v['email'];
                            $name='VDMA';
                            $subject='VDMA China: Your VDMA Wechat Account Status';
                            $content="Dear VDMA members,Thank you for using VDMA China Wechat, your account is now ready to login.Thank you for your cooperation.";
                            $this->send_mail($toemail,$name,$subject,$content);
                        }
                    }
                        return ['code'=>1,'msg'=>'修改成功'];

                }
            }else{
                return ['code'=>400,'msg'=>'修改失败'];
            }
        }
        $data = Db('user')->where('audit',0)->order('id desc')->paginate(10);
        $page = $data->render();
        $this->assign('page',$page);
        $this->assign('data',$data);
        return $this->fetch();
    }


    /**
     * 发送邮件方法
     * @param string $to：接收者邮箱地址
     * @param string $title：邮件的标题
     * @param string $content：邮件内容
     * @return boolean  true:发送成功 false:发送失败
     */
    function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null){

        //实例化PHPMailer核心类
        vendor('phpmailer.phpmailer.src');
        $mail = new \PHPMailer\PHPMailer\PHPMailer();


        $mail->CharSet = 'UTF-8';           //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
        $mail->IsSMTP();                    // 设定使用SMTP服务
        $mail->SMTPDebug = 0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
        $mail->SMTPAuth = true;             // 启用 SMTP 验证功能
        $mail->SMTPSecure = 'ssl';          // 使用安全协议
        $mail->Host = "smtp.263.net"; // SMTP 服务器
        $mail->Port = 465;                  // SMTP服务器的端口号
        $mail->Username = "info@chinavdma.org";    // SMTP服务器用户名
        $mail->Password = "vdmashanghai2017";     // SMTP服务器密码
        $mail->SetFrom('info@chinavdma.org', 'vdma');
        $replyEmail = '';                   //留空则为发件人EMAIL
        $replyName = '';                    //回复名称（留空则为发件人名称）
        $mail->AddReplyTo($replyEmail, $replyName);
        $mail->Subject = $subject;
        $mail->IsHTML(true);
        $mail->MsgHTML($body);
        $mail->AddAddress($tomail, $name);
        if (is_array($attachment)) { // 添加附件
            foreach ($attachment as $file) {
                is_file($file) && $mail->AddAttachment($file);
            }
        }
        return $mail->Send() ? true : $mail->ErrorInfo;
    }












}